import React, { Component, Fragment } from 'react'
import { Menu } from 'antd'
import MyIcon from '../Iconfont/Iconfont'
import http from '../../../api/request'
import './Menu.less'
const { SubMenu } = Menu
class LeftMenu extends Component {
  constructor(props) {
    super(props)
    this.state = {
      openKeys: ['/admin/ui'],
      menuList: [],
    }
    this.onOpenChange = this.onOpenChange.bind(this)
    this.handleClick = this.handleClick.bind(this)
  }
  componentDidMount() {
    this.getMenuList()
  }
  render() {
    return (
      <Fragment>
        <Menu
          mode="inline"
          openKeys={this.state.openKeys}
          onOpenChange={this.onOpenChange}
          style={{ width: '100%', background: '#001529', color: '#ccc' }}
          onClick={this.handleClick}
        >
          {this.state.menuList.map((content, index) => {
            if (content.children) {
              return (
                <SubMenu
                  title={content.title}
                  key={content.key}
                  icon={<MyIcon type={content.icon}></MyIcon>}
                >
                  {content.children.map((item, index2) => {
                    return (
                      <Menu.Item
                        key={item.key}
                        icon={<MyIcon type={item.icon}></MyIcon>}
                      >
                        {item.title}
                      </Menu.Item>
                    )
                  })}
                </SubMenu>
              )
            } else {
              return (
                <Menu.Item
                  key={content.key}
                  icon={<MyIcon type={content.icon}></MyIcon>}
                >
                  {content.title}
                </Menu.Item>
              )
            }
          })}
        </Menu>
      </Fragment>
    )
  }
  onOpenChange(openKeys) {
    console.log(openKeys)
    const latestOpenKey = openKeys.find(
      (key) => this.state.openKeys.indexOf(key) === -1
    )
    this.state.menuList.forEach((item, index) => {
      console.log(item.key)
      console.log(latestOpenKey)
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      })
    })
  }
  getMenuList() {
    let _this = this
    http.get('/api/menu.json').then((res) => {
      _this.setState({
        menuList: res.data,
      })
    })
  }
  handleClick(e) {
    console.log(e)
  }
}

export default LeftMenu
